/**
 * 销售退货入库单 新建或编辑页面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Sale.SREditForm", {
  extend: "PSI.AFX.Form.EditForm",

  /**
   * @override
   */
  initComponent() {
    const me = this;
    me._readonly = false;
    const entity = me.getEntity();
    me.adding = entity == null;

    const action = entity == null ? "新建" : "编辑";
    const title = me.formatTitleLabel("销售退货入库单", action);

    PCL.apply(me, {
      header: false,
      padding: "0 0 0 0",
      border: 0,
      maximized: true,
      layout: "border",
      tbar: [{
        id: me.buildId(me, "dfTitle"),
        value: title, xtype: "displayfield"
      }, "->", {
        text: "选择销售出库单",
        ...PSI.Const.BTN_STYLE,
        handler: me._onSelectWSBill,
        scope: me,
        disabled: me.entity != null
      }, "-", {
        text: "保存 <span class='PSI-shortcut-DS'>Alt + S</span>",
        tooltip: "快捷键：Alt + S",
        ...PSI.Const.BTN_STYLE,
        iconCls: "PSI-button-ok",
        handler: me._onOK,
        scope: me,
        id: me.buildId(me, "buttonSave")
      }, "-", {
        text: "取消",
        iconCls: "PSI-tb-close",
        ...PSI.Const.BTN_STYLE,
        handler() {
          if (me._readonly) {
            me.close();
            return;
          }

          me.confirm("请确认是否取消当前操作？", () => {
            me.close();
          });
        },
        scope: me,
        id: me.buildId(me, "buttonCancel")
      }, "-", {
        text: "表单通用操作指南",
        ...PSI.Const.BTN_STYLE,
        iconCls: "PSI-help",
        handler() {
          me.focus();
          window.open(me.URL("Home/Help/index?t=commBill"));
        }
      }, "-", {
        margin: "5 5 5 0",
        cls: "PSI-toolbox",
        labelWidth: 0,
        width: 90,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield"
      }],
      items: [{
        region: "center",
        border: 0,
        bodyPadding: 10,
        layout: "fit",
        items: [me.getGoodsGrid()]
      }, {
        region: "north",
        border: 0,
        layout: {
          type: "table",
          columns: 4,
          tableAttrs: PSI.Const.TABLE_LAYOUT_SMALL,
        },
        height: 105,
        bodyPadding: 10,
        items: [{
          xtype: "hidden",
          id: me.buildId(me, "hiddenId"),
          name: "id",
          value: entity == null ? null : entity.get("id")
        }, {
          id: me.buildId(me, "editCustomer"),
          xtype: "displayfield",
          fieldLabel: "客户",
          labelWidth: 60,
          labelAlign: "right",
          labelSeparator: "",
          colspan: 4,
          width: 430
        }, {
          id: me.buildId(me, "editRef"),
          fieldLabel: "单号",
          labelWidth: 60,
          labelAlign: "right",
          labelSeparator: "",
          xtype: "displayfield",
          value: me.toFieldNoteText("保存后自动生成")
        }, {
          id: me.buildId(me, "editBizDT"),
          fieldLabel: "业务日期",
          allowBlank: false,
          blankText: "没有输入业务日期",
          labelWidth: 65,
          labelAlign: "right",
          labelSeparator: "",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          xtype: "datefield",
          format: "Y-m-d",
          value: new Date(),
          name: "bizDT",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          xtype: "hidden",
          id: me.buildId(me, "editCustomerId"),
          name: "customerId"
        }, {
          id: me.buildId(me, "editWarehouse"),
          fieldLabel: "入库仓库",
          labelWidth: 65,
          labelAlign: "right",
          labelSeparator: "",
          xtype: "psi_warehousefield",
          fid: "2006",
          allowBlank: false,
          blankText: "没有输入入库仓库",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editBizUser"),
          fieldLabel: "业务员",
          xtype: "psi_userfield",
          labelWidth: 60,
          labelAlign: "right",
          labelSeparator: "",
          allowBlank: false,
          blankText: "没有输入业务员",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editPaymentType"),
          labelWidth: 60,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "付款方式",
          xtype: "combo",
          queryMode: "local",
          editable: false,
          valueField: "id",
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [["0", "记应付账款"],
            ["1", "现金付款"],
            ["2", "退款转入预收款"]]
          }),
          value: "0",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editBillMemo"),
          labelWidth: 65,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "备注",
          xtype: "textfield",
          listeners: {
            specialkey: {
              fn: me._onEditBillMemoSpecialKey,
              scope: me
            }
          },
          colspan: 3,
          width: 645
        }]
      }],
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      }
    });

    me.callParent(arguments);

    me.dfTitle = PCL.getCmp(me.buildId(me, "dfTitle"));

    me.buttonSave = PCL.getCmp(me.buildId(me, "buttonSave"));
    me.buttonCancel = PCL.getCmp(me.buildId(me, "buttonCancel"));

    me.hiddenId = PCL.getCmp(me.buildId(me, "hiddenId"));
    me.editRef = PCL.getCmp(me.buildId(me, "editRef"));
    me.editCustomer = PCL.getCmp(me.buildId(me, "editCustomer"));
    me.editCustomerId = PCL.getCmp(me.buildId(me, "editCustomerId"));
    me.editBizDT = PCL.getCmp(me.buildId(me, "editBizDT"));
    me.editWarehouse = PCL.getCmp(me.buildId(me, "editWarehouse"));
    me.editBizUser = PCL.getCmp(me.buildId(me, "editBizUser"));
    me.editPaymentType = PCL.getCmp(me.buildId(me, "editPaymentType"));
    me.editBillMemo = PCL.getCmp(me.buildId(me, "editBillMemo"));

    // AFX
    me.__editorList = [
      me.editBizDT, me.editWarehouse, me.editBizUser,
      me.editPaymentType, me.editBillMemo];


    me._keyMap = PCL.create("PCL.util.KeyMap", PCL.getBody(), {
      key: "S",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        if (me._readonly) {
          return;
        }

        me._onOK.apply(me, []);
      },
      scope: me
    });
  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;

    PCL.WindowManager.hideAll();

    // AFX
    PCL.get(window).un('beforeunload', me.__onWindowBeforeUnload);

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.enable();
    }

    me._keyMap.destroy();
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    // AFX
    PCL.get(window).on('beforeunload', me.__onWindowBeforeUnload);

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.disable();
    }

    const el = me.getEl() || PCL.getBody();
    el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/SaleRej/srBillInfo"),
      params: {
        id: me.hiddenId.getValue()
      },
      callback(options, success, response) {
        el.unmask();

        if (success) {
          me.editWarehouse.focus();

          const data = me.decodeJSON(response.responseText);

          if (data.ref) {
            // 编辑单据
            me.editRef.setValue(me.toFieldNoteText(data.ref));
            me.editCustomer.setValue(me.toFieldNoteText(data.customerName + " 销售单号: "
              + data.wsBillRef));
            me.editCustomerId.setValue(data.customerId);
          } else {
            // 这是：新建退货入库单
            // 第一步就是选中销售出库单
            me._onSelectWSBill();
          }

          me.editWarehouse.setIdValue(data.warehouseId);
          me.editWarehouse.setValue(data.warehouseName);

          me.editBizUser.setIdValue(data.bizUserId);
          me.editBizUser.setValue(data.bizUserName);
          if (data.bizDT) {
            me.editBizDT.setValue(data.bizDT);
          }
          if (data.paymentType) {
            me.editPaymentType.setValue(data.paymentType);
          }
          if (data.billMemo) {
            me.editBillMemo.setValue(data.billMemo);
          }

          const store = me.getGoodsGrid().getStore();
          store.removeAll();
          if (data.items) {
            store.add(data.items);
          }

          if (data.billStatus && data.billStatus != 0) {
            me.setBillReadonly();
          }
        } else {
          me.showInfo("网络错误")
        }
      }
    });
  },

  /**
   * @private
   */
  _onOK() {
    const me = this;
    PCL.getBody().mask("正在保存中...");
    me.ajax({
      url: me.URL("SLN0001/SaleRej/editSRBill"),
      params: {
        adding: me.adding ? "1" : "0",
        jsonStr: me.getSaveData()
      },
      callback(options, success, response) {
        PCL.getBody().unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          if (data.success) {
            me.close();
            const parentForm = me.getParentForm();
            if (parentForm) {
              parentForm.refreshMainGrid.apply(parentForm, [data.id]);
            }

            me.tip("成功保存数据", true);
          } else {
            me.showInfo(data.msg, () => {
              me.editWarehouse.focus();
            });
          }
        }
      }
    });
  },

  /**
   * @private
   */
  _onEditBillMemoSpecialKey(field, e) {
    const me = this;

    if (me._readonly) {
      return;
    }

    if (e.getKey() == e.ENTER) {
      me.getGoodsGrid().focus();
      me._cellEditing.startEdit(0, 3);
    }
  },

  /**
   * @private
   */
  getGoodsGrid() {
    const me = this;
    if (me._goodsGrid) {
      return me._goodsGrid;
    }

    const modelName = me.buildModelName(me, "SRBillDetail_EditForm");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "goodsId", "goodsCode", "goodsName",
        "goodsSpec", "unitName", "goodsCount",
        "goodsMoney", "goodsPrice", "rejCount", "rejPrice",
        {
          name: "rejMoney",
          type: "float"
        }, "sn", "memo", "rejPriceWithTax",
        {
          name: "rejMoneyWithTax",
          type: "float"
        }, "goodsPriceWithTax", "goodsMoneyWithTax", "taxRate"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._cellEditing = PCL.create("PSI.UX.CellEditing", {
      clicksToEdit: 1,
      listeners: {
        edit: {
          fn: me._onCellEditingAfterEdit,
          scope: me
        }
      }
    });

    me._goodsGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-EF",
      viewConfig: {
        enableTextSelection: true,
        markDirty: !me.adding
      },
      features: [{
        ftype: "summary"
      }],
      plugins: [me._cellEditing],
      columnLines: true,
      columns: [PCL.create("PCL.grid.RowNumberer", {
        text: "#",
        width: 30
      }), {
        header: "商品编码",
        dataIndex: "goodsCode",
        menuDisabled: true,
        draggable: false,
        sortable: false
      }, {
        header: "品名/规格型号",
        dataIndex: "goodsName",
        menuDisabled: true,
        sortable: false,
        width: 330,
        renderer(value, metaData, record) {
          return record.get("goodsName") + " " + record.get("goodsSpec");
        }
      }, {
        header: "退货数量",
        dataIndex: "rejCount",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        width: 90,
        editor: {
          xtype: "numberfield",
          allowDecimals: PSI.Const.GC_DEC_NUMBER > 0,
          decimalPrecision: PSI.Const.GC_DEC_NUMBER,
          minValue: 0,
          hideTrigger: true
        }
      }, {
        header: "单位",
        dataIndex: "unitName",
        menuDisabled: true,
        sortable: false,
        draggable: false,
        width: 60,
        align: "center"
      }, {
        header: "退货单价(含税)",
        dataIndex: "rejPriceWithTax",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 120,
        editor: {
          xtype: "numberfield",
          allowDecimals: true,
          hideTrigger: true
        },
        summaryRenderer() {
          return "金额合计";
        }
      }, {
        header: "退货金额(含税)",
        dataIndex: "rejMoneyWithTax",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 120,
        editor: {
          xtype: "numberfield",
          allowDecimals: true,
          hideTrigger: true
        },
        summaryType: "sum"
      }, {
        header: "退货单价(不含税)",
        dataIndex: "rejPrice",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 120,
        editor: {
          xtype: "numberfield",
          allowDecimals: true,
          hideTrigger: true
        }
      }, {
        header: "退货金额(不含税)",
        dataIndex: "rejMoney",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 120,
        editor: {
          xtype: "numberfield",
          allowDecimals: true,
          hideTrigger: true
        },
        summaryType: "sum"
      }, {
        header: "税率(%)",
        dataIndex: "taxRate",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        width: 60
      }, {
        header: "销售数量",
        dataIndex: "goodsCount",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        width: 90
      }, {
        header: "销售单价(不含税)",
        dataIndex: "goodsPrice",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 120
      }, {
        header: "销售金额(不含税)",
        dataIndex: "goodsMoney",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 120
      }, {
        header: "销售单价(含税)",
        dataIndex: "goodsPriceWithTax",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 120
      }, {
        header: "销售金额(含税)",
        dataIndex: "goodsMoneyWithTax",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 120
      }, {
        header: "序列号",
        dataIndex: "sn",
        menuDisabled: true,
        draggable: false,
        sortable: false
      }, {
        header: "备注",
        dataIndex: "memo",
        menuDisabled: true,
        sortable: false,
        draggable: false,
        editor: {
          xtype: "textfield"
        }
      }],
      store: store,
      listeners: {
        cellclick() {
          return !me._readonly;
        }
      }
    });

    return me._goodsGrid;
  },

  /**
   * @private
   */
  _onCellEditingAfterEdit(editor, e) {
    const me = this;
    if (me._readonly) {
      return;
    }

    const fieldName = e.field;
    const goods = e.record;
    const oldValue = e.originalValue;
    if (fieldName == "rejMoney") {
      if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
        me.calcPrice(goods);
      }
    } else if (fieldName == "rejCount") {
      if (goods.get(fieldName) != oldValue) {
        me.calcMoney(goods);
      }
    } else if (fieldName == "rejPrice") {
      if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
        me.calcMoney(goods);
      }
    } else if (fieldName == "rejPriceWithTax") {
      if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
        me.calcMoney2(goods);
      }
    } else if (fieldName == "rejMoneyWithTax") {
      if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
        me.calcPrice2(goods);
      }
    }
  },

  calcMoney(goods) {
    if (!goods) {
      return;
    }

    var rejCount = goods.get("rejCount");
    if (!rejCount) {
      rejCount = 0;
    }
    var rejPrice = goods.get("rejPrice");
    if (!rejPrice) {
      rejPrice = 0;
    }
    goods.set("rejMoney", rejCount * rejPrice);
    var taxRate = goods.get("taxRate") / 100;
    goods.set("rejMoneyWithTax", rejCount * rejPrice * (1 + taxRate));
    if (rejCount != 0) {
      goods.set("rejPriceWithTax", goods.get("rejMoneyWithTax") / rejCount);
    }
  },

  // 含税价变化
  calcMoney2(goods) {
    if (!goods) {
      return;
    }

    var rejCount = goods.get("rejCount");
    if (!rejCount) {
      rejCount = 0;
    }
    var rejPriceWithTax = goods.get("rejPriceWithTax");
    if (!rejPriceWithTax) {
      rejPriceWithTax = 0;
    }
    goods.set("rejMoneyWithTax", rejCount * rejPriceWithTax);
    var taxRate = goods.get("taxRate") / 100;

    goods.set("rejPrice", rejPriceWithTax / (1 + taxRate));
    goods.set("rejMoney", goods.get("rejPrice") * rejCount);
  },

  // 因不含税金额变化
  calcPrice(goods) {
    if (!goods) {
      return;
    }
    var rejCount = goods.get("rejCount");
    if (rejCount && rejCount != 0) {
      var taxRate = goods.get("taxRate") / 100;
      goods.set("rejPrice", goods.get("rejMoney") / rejCount);
      goods.set("rejMoneyWithTax", goods.get("rejMoney") * (1 + taxRate));
      goods.set("rejPriceWithTax", goods.get("rejMoneyWithTax") / rejCount);
    }
  },

  // 因含税金额变化
  calcPrice2(goods) {
    if (!goods) {
      return;
    }
    var rejCount = goods.get("rejCount");
    if (rejCount && rejCount != 0) {
      var taxRate = goods.get("taxRate") / 100;
      goods.set("rejPriceWithTax", goods.get("rejMoneyWithTax") / rejCount);
      goods.set("rejMoney", goods.get("rejMoneyWithTax") / (1 + taxRate));
      goods.set("rejPrice", goods.get("rejMoney") / rejCount);
    }
  },

  /**
   * @private
   */
  getSaveData() {
    const me = this;
    const result = {
      id: me.hiddenId.getValue(),
      bizDT: PCL.Date.format(me.editBizDT.getValue(), "Y-m-d"),
      customerId: me.editCustomerId.getValue(),
      warehouseId: me.editWarehouse.getIdValue(),
      bizUserId: me.editBizUser.getIdValue(),
      paymentType: me.editPaymentType.getValue(),
      billMemo: me.editBillMemo.getValue(),
      wsBillId: me._wsBillId,
      items: []
    };

    const store = me.getGoodsGrid().getStore();
    for (let i = 0; i < store.getCount(); i++) {
      const item = store.getAt(i);
      result.items.push({
        id: item.get("id"),
        goodsId: item.get("goodsId"),
        rejCount: item.get("rejCount"),
        rejPrice: item.get("rejPrice"),
        rejMoney: item.get("rejMoney"),
        rejPriceWithTax: item.get("rejPriceWithTax"),
        rejMoneyWithTax: item.get("rejMoneyWithTax"),
        taxRate: item.get("taxRate"),
        sn: item.get("sn"),
        memo: item.get("memo")
      });
    }

    return me.encodeJSON(result);
  },

  /**
   * @private
   */
  _onSelectWSBill() {
    const me = this;

    const form = PCL.create("PSI.SLN0001.Sale.SRSelectWSBillForm", {
      parentForm: me
    });
    form.show();
  },

  /**
   * @private
   */
  getWSBillInfo(id) {
    const me = this;

    me._wsBillId = id;
    const el = me.getEl() || PCL.getBody();
    el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/SaleRej/getWSBillInfoForSRBill"),
      params: {
        id
      },
      callback(options, success, response) {
        if (success) {
          const data = me.decodeJSON(response.responseText);
          me.editCustomer.setValue(me.toFieldNoteText(data.customerName + " 销售单号: "
            + data.ref));
          me.editCustomerId.setValue(data.customerId);
          me.editWarehouse.setIdValue(data.warehouseId);
          me.editWarehouse.setValue(data.warehouseName);

          const store = me.getGoodsGrid().getStore();
          store.removeAll();
          store.add(data.items);
        }

        el.unmask();
      }
    });
  },

  /**
   * @private
   */
  setBillReadonly() {
    const me = this;
    me._readonly = true;
    me.dfTitle.setValue(me.formatTitleLabel("销售退货入库单", "查看"));

    me.buttonSave.setDisabled(true);
    me.buttonCancel.setText("关闭");
    me.editBizDT.setReadOnly(true);
    me.editWarehouse.setReadOnly(true);
    me.editBizUser.setReadOnly(true);
    me.editPaymentType.setReadOnly(true);
    me.editBillMemo.setReadOnly(true);
  }
});
